<template>
  <a-modal 
    v-model:open="visible" 
    title="应用详情" 
    :footer="null" 
    width="600px"
    class="app-detail-modal"
  >
    <div class="app-detail-content">
      <!-- 应用头部信息 -->
      <div class="app-header">
        <div class="app-cover">
          <img 
            v-if="app?.cover" 
            :src="app.cover" 
            :alt="app.appName"
            class="cover-image"
          />
          <div v-else class="default-cover">
            <CodeOutlined />
          </div>
        </div>
        
        <div class="app-main-info">
          <div class="app-title-section">
            <h2 class="app-title">{{ app?.appName }}</h2>
            <div class="app-badges">
              <!-- 应用类型标签 -->
              <a-tag :color="getTypeColor(app?.codeGenType)">
                <component :is="getTypeIcon(app?.codeGenType)" />
                {{ getTypeName(app?.codeGenType) }}
              </a-tag>
              
              <!-- 精选标识 -->
              <a-tag v-if="app?.priority === 100" color="gold">
                <StarFilled />
                精选应用
              </a-tag>
              
              <!-- 部署状态 -->
              <a-tag v-if="app?.deployKey" color="green">
                <RocketOutlined />
                已部署
              </a-tag>
              
              <!-- 公开状态 -->
              <a-tag :color="app?.isPublic === 1 ? 'blue' : 'default'">
                <EyeOutlined v-if="app?.isPublic === 1" />
                <EyeInvisibleOutlined v-else />
                {{ app?.isPublic === 1 ? '公开' : '私有' }}
              </a-tag>
            </div>
          </div>
          
          <div class="app-description">
            <p>{{ app?.initPrompt || '暂无描述' }}</p>
          </div>
        </div>
      </div>

      <!-- 详细信息 -->
      <div class="app-details">
        <a-row :gutter="[16, 16]">
          <!-- 创建者信息 -->
          <a-col :span="24">
            <div class="detail-section">
              <h3 class="section-title">
                <UserOutlined />
                创建者信息
              </h3>
              <div class="creator-info">
                <a-avatar :src="app?.user?.userAvatar" :size="40">
                  {{ app?.user?.userName?.charAt(0) }}
                </a-avatar>
                <div class="creator-details">
                  <div class="creator-name">
                    {{ app?.user?.userName }}
                    <a-tag v-if="app?.user?.userRole === 'admin'" color="gold" size="small">
                      <CrownOutlined />
                      管理员
                    </a-tag>
                  </div>
                  <div class="creator-account">{{ app?.user?.userAccount }}</div>
                  <div v-if="app?.user?.userProfile" class="creator-profile">
                    {{ app?.user?.userProfile }}
                  </div>
                </div>
              </div>
            </div>
          </a-col>

          <!-- 时间信息 -->
          <a-col :span="12">
            <div class="detail-section">
              <h3 class="section-title">
                <ClockCircleOutlined />
                时间信息
              </h3>
              <div class="time-info">
                <div class="time-item">
                  <span class="time-label">创建时间：</span>
                  <span class="time-value">{{ formatTime(app?.createTime) }}</span>
                </div>
                <div class="time-item">
                  <span class="time-label">最后编辑：</span>
                  <span class="time-value">{{ formatTime(app?.editTime) }}</span>
                </div>
                <div v-if="app?.deployedTime" class="time-item">
                  <span class="time-label">部署时间：</span>
                  <span class="time-value">{{ formatTime(app?.deployedTime) }}</span>
                </div>
              </div>
            </div>
          </a-col>

          <!-- 应用信息 -->
          <a-col :span="12">
            <div class="detail-section">
              <h3 class="section-title">
                <InfoCircleOutlined />
                应用信息
              </h3>
              <div class="app-info">
                <div class="info-item">
                  <span class="info-label">应用ID：</span>
                  <span class="info-value">{{ app?.id }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">应用类型：</span>
                  <span class="info-value">{{ getTypeName(app?.codeGenType) }}</span>
                </div>
                <div v-if="app?.deployKey" class="info-item">
                  <span class="info-label">部署标识：</span>
                  <span class="info-value">{{ app.deployKey }}</span>
                </div>
              </div>
            </div>
          </a-col>
        </a-row>
      </div>

      <!-- 公开状态管理（仅创建者和管理员可见） -->
      <div v-if="canManageApp" class="public-status-section">
        <div class="section-header">
          <h3 class="section-title">
            <SettingOutlined />
            应用设置
          </h3>
        </div>
        
        <div class="setting-item">
          <div class="setting-info">
            <div class="setting-title">
              <EyeOutlined v-if="app?.isPublic === 1" />
              <EyeInvisibleOutlined v-else />
              公开状态
            </div>
            <div class="setting-desc">
              {{ app?.isPublic === 1 ? '应用已在应用广场公开展示' : '应用仅自己可见，开启后将在应用广场展示' }}
            </div>
          </div>
          <a-switch 
            :checked="app?.isPublic === 1" 
            @change="handlePublicToggle"
            :loading="publicToggleLoading"
            checked-children="公开"
            un-checked-children="私有"
          />
        </div>
      </div>

      <!-- 操作栏（仅本人或管理员可见） -->
      <div v-if="showActions" class="app-actions">
        <div class="action-buttons">
          <a-button type="primary" @click="handleEdit">
            <template #icon>
              <EditOutlined />
            </template>
            编辑应用
          </a-button>
          
          <a-button v-if="!app?.deployKey" @click="handleDeploy">
            <template #icon>
              <RocketOutlined />
            </template>
            部署应用
          </a-button>
          
          <a-popconfirm
            title="确定要删除这个应用吗？"
            description="删除后无法恢复，请谨慎操作"
            @confirm="handleDelete"
            ok-text="确定删除"
            cancel-text="取消"
          >
            <a-button danger>
              <template #icon>
                <DeleteOutlined />
              </template>
              删除应用
            </a-button>
          </a-popconfirm>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { message } from 'ant-design-vue'
import {
  EditOutlined,
  DeleteOutlined,
  UserOutlined,
  ClockCircleOutlined,
  InfoCircleOutlined,
  SettingOutlined,
  CodeOutlined,
  StarFilled,
  RocketOutlined,
  EyeOutlined,
  EyeInvisibleOutlined,
  CrownOutlined,
  GlobalOutlined,
  MobileOutlined,
  DesktopOutlined,
  ApiOutlined
} from '@ant-design/icons-vue'
import { formatTime } from '@/utils/time'
import { updateAppPublicStatus } from '@/api/yingyongjiekou'
import { useLoginUserStore } from '@/stores/loginUser'

interface Props {
  open: boolean
  app?: API.AppVO
  showActions?: boolean
}

interface Emits {
  (e: 'update:open', value: boolean): void
  (e: 'edit'): void
  (e: 'delete'): void
  (e: 'deploy'): void
  (e: 'publicToggle', isPublic: boolean): void
}

const props = withDefaults(defineProps<Props>(), {
  showActions: false
})

const emit = defineEmits<Emits>()
const loginUserStore = useLoginUserStore()
const publicToggleLoading = ref(false)

const visible = computed({
  get: () => props.open,
  set: value => emit('update:open', value)
})

// 判断是否可以管理该应用
const canManageApp = computed(() => {
  if (!props.app || !loginUserStore.loginUser.id) return false
  return loginUserStore.loginUser.userRole === 'admin' || 
         props.app.userId === loginUserStore.loginUser.id
})

// 获取应用类型图标
const getTypeIcon = (type?: string) => {
  const iconMap = {
    vue: CodeOutlined,
    web: GlobalOutlined,
    mobile: MobileOutlined,
    desktop: DesktopOutlined,
    api: ApiOutlined
  }
  return iconMap[type as keyof typeof iconMap] || CodeOutlined
}

// 获取应用类型名称
const getTypeName = (type?: string) => {
  const nameMap = {
    vue: 'Vue应用',
    web: 'Web应用',
    mobile: '移动应用',
    desktop: '桌面应用',
    api: 'API服务'
  }
  return nameMap[type as keyof typeof nameMap] || '应用'
}

// 获取应用类型颜色
const getTypeColor = (type?: string) => {
  const colorMap = {
    vue: 'green',
    web: 'blue',
    mobile: 'purple',
    desktop: 'orange',
    api: 'cyan'
  }
  return colorMap[type as keyof typeof colorMap] || 'default'
}

// 处理公开状态切换
const handlePublicToggle = async (checked: boolean) => {
  if (!props.app?.id) return
  
  publicToggleLoading.value = true
  try {
    const response = await updateAppPublicStatus({
      appId: props.app.id,
      isPublic: checked ? 1 : 0
    })
    
    if (response.data.code === 200) {
      message.success(checked ? '应用已公开' : '应用已设为私有')
      emit('publicToggle', checked)
    } else {
      message.error(response.data.message || '操作失败')
    }
  } catch (error) {
    console.error('切换公开状态失败:', error)
    message.error('操作失败，请重试')
  } finally {
    publicToggleLoading.value = false
  }
}

const handleEdit = () => {
  emit('edit')
}

const handleDelete = () => {
  emit('delete')
}

const handleDeploy = () => {
  emit('deploy')
}
</script>

<style scoped>
.app-detail-content {
  padding: 8px 0;
}

.app-header {
  display: flex;
  gap: 20px;
  margin-bottom: 24px;
  align-items: center;
}

.app-cover {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
  background-color: #f0f0f0;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #eee;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-cover {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #888;
  font-size: 30px;
}

.app-main-info {
  flex-grow: 1;
}

.app-title-section {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.app-title {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.app-badges {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.app-description {
  font-size: 16px;
  color: #666;
  line-height: 1.6;
  margin-top: 10px;
}

.app-details {
  margin-top: 24px;
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.detail-section {
  margin-bottom: 16px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-size: 16px;
  color: #333;
}

.creator-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.creator-details {
  display: flex;
  flex-direction: column;
}

.creator-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  display: flex;
  align-items: center;
  gap: 5px;
}

.creator-account {
  font-size: 14px;
  color: #666;
  margin-top: 2px;
}

.creator-profile {
  font-size: 14px;
  color: #999;
  margin-top: 4px;
}

.time-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.time-item {
  display: flex;
  align-items: center;
}

.time-label {
  width: 80px;
  color: #666;
  font-size: 14px;
  flex-shrink: 0;
}

.time-value {
  font-size: 14px;
  color: #333;
}

.app-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-label {
  width: 80px;
  color: #666;
  font-size: 14px;
  flex-shrink: 0;
}

.info-value {
  font-size: 14px;
  color: #333;
}

.public-status-section {
  margin-top: 24px;
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.setting-info {
  display: flex;
  flex-direction: column;
}

.setting-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  color: #333;
  font-weight: bold;
}

.setting-desc {
  font-size: 14px;
  color: #999;
  margin-top: 4px;
}

.app-actions {
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.action-buttons {
  display: flex;
  gap: 10px;
}
</style>
